package com.by_man.presenter.module_bluetooth;


import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.by_man.presenter.R;
import com.by_man.presenter.SharedApplication;
import com.by_man.presenter.module_health_management.measure_blood_pressure.MeasureBloodPressureActivity;
import com.by_man.repository.IpAddress;
import com.by_man.repository.LocalDataManager;
import com.by_man.repository.PostStringRequest;
import com.by_man.repository.UserInfos;
import com.google.gson.Gson;


import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class BppDemo extends ActionBarActivity {
    private static String mDevAddr_backup = null;
    private android.support.v7.widget.Toolbar mtoolbar;
    public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";
    public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";
    private static final String TAG = BppDemo.class.getSimpleName();
    private BluetoothLeService bleService;
    private BluetoothLeService disconnect=new BluetoothLeService();
    Button btnTim;
    Button btnTim2;
    private BluetoothGattCharacteristic charaSppleNotify;
    private BluetoothGattCharacteristic charaSppleWrite;
    private BluetoothGatt mConnGatt;
    private byte[] cmd = new byte[32];
    private byte cmd_idx;
    private TextView heartrate;
    private TextView pre_high;
    private TextView pre_low,pre_pro;
    private String mDevAddr;
    private String mDevName;
    private String high;
    private String low;
    private String xinlv;
    private FrameLayout flayout;
    private int view1;
    private int view2;
    private int view3;
    private LinearLayout linear;
    private LinearLayout cuowu;

    private boolean updataor=false;
    private boolean andor=true;
    private boolean connect = false;
    private Handler mHandler;


    private ProgressDialog progressDialog;


    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            String str = intent.getAction();
            if ("com.example.bluetooth.le.ACTION_GATT_CONNECTED".equals(str)) {
                Log.i("onreceive onrecrive", "Connected");
                // displayGattServices(bleService.getSupportedGattServices());
            } else if ("com.example.bluetooth.le.ACTION_GATT_DISCONNECTED".equals(str)) {
                Log.e("onreceive onrecrive", "DISConnected");
            } else if ("com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED".equals(str)) {
                displayGattServices(bleService.getSupportedGattServices());
            } else if ("com.example.bluetooth.le.ACTION_DATA_AVAILABLE".equals(str)) {
                byte[] value = intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA);
                if (value != null && value.length > 0) {
                   // Log.i("", Arrays.toString(value));
                    parseData(value);

                }
                if(updataor&&andor){updata();andor=false;}

            }


        }


    };

    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName paramComponentName, IBinder paramIBinder) {
            bleService = ((BluetoothLeService.LocalBinder) paramIBinder).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e(TAG, "onServiceDisconnected");

        }
    };

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void displayGattServices(List<BluetoothGattService> paramList) {

        if (paramList == null) {
            Log.i(TAG, "null");
            return;
        }
        Iterator localIterator1 = paramList.iterator();
        if (!localIterator1.hasNext()) {
            Log.i(TAG, "list null");
        }

        while (localIterator1.hasNext()) {
            BluetoothGattService localBluetoothGattService = (BluetoothGattService) localIterator1.next();
            List localList = localBluetoothGattService.getCharacteristics();

            if (this.bleService.UUID_SPPLE_SERV.equals(localBluetoothGattService.getUuid()))
                {
                Log.e(TAG, "UUID_SPPLE_SERV");
                  Iterator localIterator2 = localList.iterator();

                    while (localIterator2.hasNext()) {

                    BluetoothGattCharacteristic localBluetoothGattCharacteristic =
                            (BluetoothGattCharacteristic) localIterator2.next();
                    if (this.bleService.UUID_SPPLE_WRITE.equals(localBluetoothGattCharacteristic.getUuid())) {
                        this.charaSppleWrite = localBluetoothGattCharacteristic;
                        Log.e(TAG, "UUID_SPPLE_WRITE");
                    } else if (this.bleService.UUID_SPPLE_NOTIFY.equals(localBluetoothGattCharacteristic.getUuid())) {
                        this.charaSppleNotify = localBluetoothGattCharacteristic;
                        this.bleService.setCharacteristicNotification(this.charaSppleNotify, true);
                        Log.e(TAG, "UUID_SPPLE_NOTIFY");
                        progressDialog.cancel();
                        connect = true;
                    }
                }
            }
        }
    }

    private static IntentFilter makeGattUpdateIntentFilter() {
        IntentFilter localIntentFilter = new IntentFilter();
        localIntentFilter.addAction("com.example.bluetooth.le.ACTION_GATT_CONNECTED");
        localIntentFilter.addAction("com.example.bluetooth.le.ACTION_GATT_DISCONNECTED");
        localIntentFilter.addAction("com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED");
        localIntentFilter.addAction("com.example.bluetooth.le.ACTION_DATA_AVAILABLE");
        return localIntentFilter;
    }


    protected void onCreate(Bundle paramBundle) {

        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        super.onCreate(paramBundle);
        setContentView(R.layout.content_bppdemo);//bppdemo_layout
        Intent localIntent = getIntent();
        setProgressBarVisibility(true);
        initView();

        this.mHandler = new Handler();
        checkbooth();

        flayout=(FrameLayout)findViewById(R.id.flayout);
        cuowu=(LinearLayout) findViewById(R.id.cuowutishi);
        linear=(LinearLayout)findViewById(R.id.xianshi);









        //蓝牙相关
        this.mDevName = localIntent.getStringExtra("DEVICE_NAME");
        this.mDevAddr = localIntent.getStringExtra("DEVICE_ADDRESS");
        Intent data = new Intent(this, BluetoothLeService.class);
        data.putExtra("mac_address", mDevAddr);
        bindService(data, this.mServiceConnection, Context.BIND_AUTO_CREATE);

        this.pre_high = ((TextView) findViewById(R.id.tv1));//高压
        this.pre_low = ((TextView) findViewById(R.id.tv2));
        this.pre_pro=((TextView)findViewById(R.id.xueyaxueya));//低压
        this.heartrate = ((TextView) findViewById(R.id.tv3));//心率
        this.btnTim = ((Button) findViewById(R.id.ib1));

        this.btnTim.setOnClickListener(new View.OnClickListener() {
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
            @Override
            public void onClick(View paramView) {



                andor=true;

                view1=flayout.getVisibility();
                //view2=linear.getVisibility();
                view3=cuowu.getVisibility();

                if(view1==4||view3==0)
                {
                    flayout.setVisibility(View.VISIBLE);
                    linear.setVisibility(View.INVISIBLE);
                    cuowu.setVisibility(View.INVISIBLE);
                }



                byte[] arrayOfByte = new byte[6];
                arrayOfByte[0] = -2;
                arrayOfByte[1] = -127;
                arrayOfByte[5] = 1;
                if (charaSppleWrite != null) {

                    charaSppleWrite.setValue(arrayOfByte);
                    bleService.writeCharacteristic(charaSppleWrite);
                    pre_high.setText("");
                    heartrate.setText("");
                    pre_low.setText("");
                    pre_pro.setText("0");
                }else {


                    Toast.makeText(BppDemo.this,"请选择正确的蓝牙设备",Toast.LENGTH_SHORT).show();
                }



            }
        });
        this.btnTim2 = ((Button) findViewById(R.id.ib2));
        this.btnTim2.setOnClickListener(
                new View.OnClickListener() {
                    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
                    @Override
                    public void onClick(View paramView) {
                        andor=true;

                        view1=flayout.getVisibility();
                        view2=linear.getVisibility();
                        view3=cuowu.getVisibility();



                        if(view1==4||view3==0)
                        {
                            flayout.setVisibility(View.VISIBLE);
                            linear.setVisibility(View.INVISIBLE);
                            cuowu.setVisibility(View.INVISIBLE);
                        }


                        byte[] arrayOfByte = new byte[6];
                        arrayOfByte[0] = -2;
                        arrayOfByte[1] = -127;
                        arrayOfByte[5] = 1;
                        Log.e("arrayOfByte", "");
                        if (charaSppleWrite != null) {
                            charaSppleWrite.setValue(arrayOfByte);
                            bleService.writeCharacteristic(charaSppleWrite);
                            pre_high.setText("");
                            heartrate.setText("");
                            pre_low.setText("");
                            pre_pro.setText("0");

                        }else {
                            Toast.makeText(BppDemo.this,"请选择正确的蓝牙设备",Toast.LENGTH_SHORT).show();
                        }

                    }
                });


    }
    private void checkbooth(){

        this.mHandler.postDelayed(new Runnable()
                                  {
                                      @Override
                                      public void run() {

                                          if (!connect)
                                          {
                                              Log.e("zaizaizaizai","paopaoapaoapoa");
                                              progressDialog.cancel();
                                              Toast.makeText(BppDemo.this,"蓝牙连接失败，请重新选择设备。",Toast.LENGTH_LONG).show();
                                          }

                                      }

                                  }
                , 10000L);


    }

    protected void onDestroy() {
        super.onDestroy();
        this.bleService = null;

    }

    protected void onPause() {
        super.onPause();
        mDevAddr_backup=mDevAddr;

    }
    protected void onStop() {
        super.onStop();
        bleService.close();



    }
    protected void onStart()
    {
        super.onStart();
        if(mDevAddr_backup!=null)
        {
            mDevAddr=mDevAddr_backup;
        }
        Intent intent = new Intent(this, BluetoothGattService.class);
        intent.putExtra("mac_address", mDevAddr);
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);

    }

    protected void onResume() {
        super.onResume();
        registerReceiver(this.mGattUpdateReceiver, makeGattUpdateIntentFilter());//必须在这
        if (this.bleService != null)
        {
            boolean bool = this.bleService.connect(this.mDevAddr);
            Log.e(TAG, "Connect request result=" + bool);

        }






    }
    private void parseData(byte[] paramArrayOfByte) {

        Log.e("jinjin", Arrays.toString(paramArrayOfByte));



        for(int i=0;i<paramArrayOfByte.length;i++)
        {


            if ((paramArrayOfByte[i]==(-124))&&i<paramArrayOfByte.length-2&&paramArrayOfByte.length<=12)
            {
                this.pre_pro.setText(Integer.toString(0xFF & paramArrayOfByte[i+2]));
                break;
            }


            if (((paramArrayOfByte[i]==(-128))||(paramArrayOfByte[i]==(-127)))&&i<paramArrayOfByte.length-3&&paramArrayOfByte.length>12)
            {
                this.pre_high.setText(Integer.toString(0xFF & paramArrayOfByte[i + 1]));
                this.pre_low.setText(Integer.toString(0xFF & paramArrayOfByte[i+2]));
                this.heartrate.setText(Integer.toString(0xFF & paramArrayOfByte[i +3]));
                this.pre_pro.setText("0");
                flayout.setVisibility(View.INVISIBLE);
                linear.setVisibility(View.VISIBLE);
                updataor=true;
                break;
            }
            if ( paramArrayOfByte[i]==(-125) &&paramArrayOfByte.length<=6&&i==1)
            {

                    flayout.setVisibility(View.INVISIBLE);
                    linear.setVisibility(View.INVISIBLE);
                    cuowu.setVisibility(View.VISIBLE);
                    break;

            }

        }


    }
    private void initView() {

        progressDialog = new ProgressDialog(BppDemo.this);
        progressDialog.setTitle("提示信息");
        progressDialog.setMessage("蓝牙正在连接，请稍后......");
        progressDialog.setCancelable(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.show();

        mtoolbar = (android.support.v7.widget.Toolbar) this.findViewById(R.id.tool_bar_jiakang);
        //初始化ToolBar
        mtoolbar.setTitle("");
        setSupportActionBar(mtoolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeAsUpIndicator(R.drawable.icon_back);
        actionBar.setDisplayHomeAsUpEnabled(true);


    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                unbindService(mServiceConnection);
                Intent intent = new Intent(BppDemo.this, MeasureBloodPressureActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK) { //监控/拦截/屏蔽返回键

            Log.e("nonono","111111");

            /*Intent intent=new Intent(BppDemo.this,FirstActivity_xycl.class);
            startActivity(intent);*/
        }
        return super.onKeyDown(keyCode, event);
    }


    private void updata()
    {


        high = pre_high.getText().toString().trim();
        low = pre_low.getText().toString().trim();
        xinlv = heartrate.getText().toString().trim();
        List<Map<String, Object>> testlist = new ArrayList<Map<String, Object>>();
        Map<String, Object> test1 = new HashMap<String, Object>();
        test1.put("id", 1);
        test1.put("type",1);
        test1.put("value", high);
        test1.put("time", gettime());
        testlist.add(test1);
        Map<String, Object> test2 = new HashMap<String, Object>();
        test2.put("id", 2);
        test2.put("type",1);
        test2.put("value", low);
        test2.put("time", gettime());
        testlist.add(test2);
        Map<String, Object> test4 = new HashMap<String, Object>();
        test4.put("id", 4);
        test4.put("type",1);
        test4.put("value", xinlv);
        test4.put("time", gettime());
        testlist.add(test4);
        String tokenTest = UserInfos.token;
        Gson gson = new Gson();
        String dataString = gson.toJson(testlist).toString();
        String datamap = "&token=" + tokenTest + "&json=" + dataString;
        //零数据不入库
        if (high.length() == 0&&low.length()==0&&xinlv.length()==0) {
            Toast.makeText(BppDemo.this, "数据为空,不允许上传，请测量后点击上传!", Toast.LENGTH_SHORT).show();
        } else {
            BppDemo.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(BppDemo.this, "数据上传成功!", Toast.LENGTH_SHORT).show();
                }
            });
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("token", tokenTest);
            params.put("json", dataString);
            PostStringRequest stringRequest = new PostStringRequest(Request.Method.POST, IpAddress.Manual_BloodPressure_Record,
                    params, new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            if (response.equalsIgnoreCase("failed")) {
                                Toast.makeText(BppDemo.this, "database failed  ", Toast.LENGTH_SHORT).show();
                            } else {
                                JSONObject json = null;
                                try {
                                    json = new JSONObject(response);
                                    boolean isFull = false;
                                    isFull = json.getBoolean("isFull");
                                    Intent intent = null;
                                    if (isFull) {
                                        Toast.makeText(BppDemo.this, "数据上传成功!", Toast.LENGTH_SHORT).show();
                                        // 更新数据
                                        LocalDataManager.getNetworkDataManager().getOneBloodPressureRecordByNetwork();
                                        LocalDataManager.getNetworkDataManager().getAllBloodPressreRecordByNetword();
                                    }

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            Log.e("BppDemoError", volleyError.getMessage(), volleyError);
                            Toast.makeText(BppDemo.this, "数据回传失败！", Toast.LENGTH_SHORT).show();
                        }
                    });
            LocalDataManager.getRequestQueue().add(stringRequest);
        }


    }

    private String gettime(){

        Calendar c = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        final String sFormat = sdf.format(c.getTime());
        Log.e("time++++++++++++++++",sFormat);
        return sFormat;
    }





}